package top.caozj.conf;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hivemq.client.mqtt.mqtt3.Mqtt3BlockingClient;
import lombok.extern.log4j.Log4j2;
import top.caozj.App;
import top.caozj.util.NoDataPolicy;
import top.caozj.util.impl.DefaultNoDataPolicy;
import top.caozj.util.impl.FixedValue;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Copyright (c) 2010, 2025, xjk All rights reserved.
 *
 * @author caozj thucaozj@outlook.com
 * @version 1.0
 * @date 2025-03-25
 * @since 20
 */
@Log4j2
public class AppConfig {
    public static List<Datasource> datasource=new ArrayList<>();
    public static MqttConf mqttConf;

    //任务执行间隔，单位 分钟
    public static int TASK_INTERVAL = 10;

    //SQL查询时间间隔，单位 分钟
    public static int SQL_INTERVAL = 10;

    //数据库传感器，系统编号
    //sensorCodeMap.put("RTD-BJ-001","wd01");
    public static HashMap<String,String> sensorCodeMap=new HashMap<>();

    //数据库传感器，设备类型
    //sensorType.put("RTD-BJ-001","RSG");
    public static HashMap<String,String> sensorType = new HashMap<>();

    //数据库查询无结果时，处理方式 ignore / fixed ,
    //如果是fixed，则需要配置fixedValue
    public static NoDataPolicy noDataPolicyObject = new DefaultNoDataPolicy();
    public static double fixedValue = 0f;

    public static boolean DEBUG = false;

    public static void init(String configFile) {

        log.info( "load configuration file" );

        ObjectMapper mapper = new ObjectMapper();

        List<Datasource> datasources = AppConfig.datasource;


        try {
            JsonNode jsonNode = mapper.readTree(new File(configFile));
//            System.out.println(jsonNode);

            //数据源配置
            JsonNode datasourceJsonNode = jsonNode.get("datasource");
            //System.out.println("datasources = " + datasources);


            //迭代所有数据源
            datasourceJsonNode.elements().forEachRemaining(node -> {

                //System.out.println("node = " + node);
                //数据源
                Datasource datasource = new Datasource(
                        node.get("type").asText(),
                        node.get("url").asText(),
                        node.get("username").asText(),
                        node.get("password").asText()
                );

                datasources.add(datasource);


                //迭代获取一个数据源下面所有查询语句
                JsonNode dataQuery = node.get("dataQuery");

                dataQuery.elements().forEachRemaining(dataQueryNode -> {
                    String datetimeFormatter="";
                    JsonNode datetimeNode1 = dataQueryNode.get("datetime");
                    if (datetimeNode1 == null){
                        datetimeFormatter = "yyyy-MM-dd HH:mm:ss";
                        System.out.println("datetimeFormatter is null, use default value: " + datetimeFormatter);
                    }else {
                        datetimeFormatter = datetimeNode1.asText();
                    }
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(datetimeFormatter);

                    String sql = dataQueryNode.get("sql").asText();
                    datasource.addDataQuery(new DataQuery(sql, dateTimeFormatter));
                });
            });

            int size = datasources.size();
            for (int i = 0; i < size; i++) {
                Datasource datasource = datasources.get(i);
            }

            //获取mqtt服务器配置

            JsonNode mqttConfJsonNode = jsonNode.get("mqtt");
            String host = mqttConfJsonNode.get("host").asText();
            int port = mqttConfJsonNode.get("port").asInt();
            String topic = mqttConfJsonNode.get("topic").asText();
            String username = mqttConfJsonNode.get("username").asText();
            String password = mqttConfJsonNode.get("password").asText();
            mqttConf = new MqttConf(host, port, topic, username, password);
            log.info("load mqtt server configuration: {}", mqttConf);
            //System.out.println("mqttConf = " + mqttConf);

            //调试模式
            JsonNode debugMode = jsonNode.get("debug");
            if (debugMode != null ){
                DEBUG = debugMode.asBoolean();
                SQL_INTERVAL=30;
            }

            //数据无结果处理方式
            JsonNode nodataPolicyNode = jsonNode.get("nodataPolicy");
            if (nodataPolicyNode != null ){
               String noDataPolicyStr = nodataPolicyNode.asText("ignore");
               if ("fixed".equalsIgnoreCase(noDataPolicyStr)){
                   noDataPolicyObject = new FixedValue();
               }else {
                   noDataPolicyObject = new DefaultNoDataPolicy();
               }
            }

            //数据无结果处理方式为固定值时的配置
            JsonNode fixedValueNode = jsonNode.get("fixedValue");
            if (fixedValueNode != null ){
                fixedValue = fixedValueNode.asDouble(0f);
            }



        } catch (Exception e) {
            e.printStackTrace();
            log.error("load config file fail");
        }


    }


    /**
     * 初始化传感器编号和系统编号的映射关系
     * 从配置文件中map.csv中读取传感器的映射关系
     */
    public static void initSensorMap(String configFile) {
        log.info( "load sensor configuration file" );
        File file = new File(configFile);
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));

        while (br.ready()){
            String s = br.readLine();
            String[] split = s.split(",");

//            sensorCodeMap.put("RTD-BJ-001","wd01");
            sensorCodeMap.put(split[1],split[0]);
            sensorType.put(split[1],split[2]);

        }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("load sensor configuration failed");
        }catch (Exception e){
            log.error("unknown exception ");
        }
    }

}
